    //
//  ComposeViewController.m
//  Jacksms-Iphone
//
//  Created by Daniele Ciriello on 15/11/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "ComposeViewController.h"


@implementation ComposeViewController

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/

/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/


- (NSString*)formatPhoneNumber:(NSString *)nb {
	NSMutableString *ret=[NSMutableString stringWithCapacity:[nb length]];
	[ret setString: nb];
	//replaceOccurrencesOfString:withString:options:range:
	[ret replaceOccurrencesOfString:@"+39" withString:@"" options:NSLiteralSearch range:NSMakeRange(0, [ret length])];
	[ret replaceOccurrencesOfString:@"(" withString:@"" options:NSLiteralSearch range:NSMakeRange(0, [ret length])];
	[ret replaceOccurrencesOfString:@")" withString:@"" options:NSLiteralSearch range:NSMakeRange(0, [ret length])];
	[ret replaceOccurrencesOfString:@"," withString:@"" options:NSLiteralSearch range:NSMakeRange(0, [ret length])];
	[ret replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:NSMakeRange(0, [ret length])];
	[ret replaceOccurrencesOfString:@"*" withString:@"" options:NSLiteralSearch range:NSMakeRange(0, [ret length])];
	[ret replaceOccurrencesOfString:@"#" withString:@"" options:NSLiteralSearch range:NSMakeRange(0, [ret length])];
	[ret replaceOccurrencesOfString:@"-" withString:@"" options:NSLiteralSearch range:NSMakeRange(0, [ret length])];
	[ret replaceOccurrencesOfString:@"+" withString:@"" options:NSLiteralSearch range:NSMakeRange(0, [ret length])];
	return ret;
}

- (NSString*)extractPhoneNumber:(NSString *)prefix number:(NSString *)number {
	NSMutableString *ret=[NSMutableString stringWithCapacity:[number length]];
	[ret setString: number];
	[ret replaceOccurrencesOfString:prefix withString:@"" options:NSLiteralSearch range:NSMakeRange(0, [ret length])];
	return ret;
}

- (void) showAlert:(NSString*)text
{
    UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"Messaggio" message:text delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alertView show];
    [alertView release];
}

- (void) showError:(NSString*)text
{
    UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"Errore" message:text delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alertView show];
    [alertView release];
}
/*
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
	if ([text isEqualToString:@"\n"]) {
		// User typed 'Done' button, so hide keyboard
		[smsTextView resignFirstResponder];			
	}
	
	//[labelCharLeft setText:text];
	
	if ([text isEqualToString:@""]) {
		//BackSpace
		return YES;
	} else  if ([smsTextView.text length] >= SMS_MAX_CHAR) {
		return NO;
	} else {
		return YES;
	}
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
	// return NO to not change text
	
	if ([string isEqualToString:@""]) {
		//BackSpace
		return YES;
	} else  if ([smsPhoneNumber.text length] >= PHONE_MAX_CHAR) {
		return NO;
	} else {
		return YES;
	}
} 

- (IBAction)deactivateKeyboard {
	[self.view resignFirstResponder];
}



- (IBAction)erasePhoneNumber {
	[smsPhoneNumber setText:@""];
}

- (IBAction)browseContactList{
	//[self showAlert:@"contatti!"];
	ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init]; 
	picker.peoplePickerDelegate = self; 
	[self presentModalViewController:picker animated:YES]; 
	[picker release]; 
	
}

- (void)peoplePickerNavigationControllerDidCancel: (ABPeoplePickerNavigationController *)peoplePicker { 
	[self dismissModalViewControllerAnimated:YES]; 
} 

- (BOOL)peoplePickerNavigationController: (ABPeoplePickerNavigationController *)peoplePicker 
	  shouldContinueAfterSelectingPerson:(ABRecordRef)person { 
	
	return YES; 
} 

- (BOOL)peoplePickerNavigationController: 
(ABPeoplePickerNavigationController *)peoplePicker 
	  shouldContinueAfterSelectingPerson:(ABRecordRef)person 
								property:(ABPropertyID)property 
							  identifier:(ABMultiValueIdentifier)identifier{ 
	
	if (property==kABPersonPhoneProperty){
		ABMutableMultiValueRef multi = ABMultiValueCreateMutable(kABMultiStringPropertyType);
		multi = ABRecordCopyValue(person, kABPersonPhoneProperty);
		
		int valueIdx=(int)ABCMultiValueIndexForIdentifier(multi, identifier);
		NSString* phoneNumber =(NSString *)ABMultiValueCopyValueAtIndex(multi, valueIdx);
		smsPhoneNumber.text = [self formatPhoneNumber:phoneNumber];
		[phoneNumber release]; 
		
		[self dismissModalViewControllerAnimated:YES]; 
		return NO; 
		
	}
	else
	{
		return YES;
	}
	
} 

- (IBAction)sendSms{
	
	if (([smsPhoneNumber.text length]==9 || [smsPhoneNumber.text length]==10) && [smsTextView.text length]>0){
		[self sendSmsToInternet:smsPhoneNumber.text smsText:smsTextView.text];	
	} else {
		
		if (([smsPhoneNumber.text length]!=9 && [smsPhoneNumber.text length]!=10 && [smsPhoneNumber.text length]!=0)){
			[self showError:@"Attenzione! Il numero di cellulare inserito non è valido!"];
			return;
		}
		
		if ([smsPhoneNumber.text length]==0){
			[self showError:@"Attenzione! Il numero di cellulare è obbligatorio!"];
			return;
		}
		if ([smsTextView.text length]==0){
			[self showError:@"Attenzione! Il testo è obbligatorio!"];
			return;
		}
		
	}
}

- (void) sendSmsToInternet:(NSString*)number smsText:(NSString*)text
{
	
	NSString* prefix = [number substringToIndex:3];
	NSString* phone = [self extractPhoneNumber:prefix number:number];
	
	
	sendSmsButton.enabled = YES;
	[activityIndicator startAnimating];
	[labelSendStatus setText:@"Invio sms in corso..."]; 
	
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; 
	NSString *username  = [defaults stringForKey:@"username_preference"];
	NSString *password  = [defaults stringForKey:@"password_preference"];
	
	NSString *post = [NSString stringWithFormat:@"username=%@&passw=%@&prefisso=%@&numero=%@&testo=%@", username, password, prefix, phone, text];
	
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
	
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
	
    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
	[request setURL:[NSURL URLWithString:@"http://www.xxx.asp"]];
	
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];
    
    NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request delegate:self];
    if (conn) 
    {
        receivedData = [[NSMutableData data] retain];
    } 
    else 
    {
        // inform the user that the download could not be made
		[labelSendStatus setText:@"Impossibile inviare sms."]; 
		[self showAlert:@"Mancata connessione a internet: non è stato possibile inviare l'sms."];
		[activityIndicator stopAnimating];
    }
}

*/
- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end
